﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceProcess;
using Microsoft.Win32;
using System.IO;
using System.Configuration;

namespace WindowsManager
{
    public partial class WindowsService : Form
    {
        //构造方法
        public WindowsService()
        {
            InitializeComponent();
        }
	//构造方法
        string ServiceNames = null;
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //开机是否自动启动
                //获得文件的当前路径   
                string dir = Directory.GetCurrentDirectory();
                //获取可执行文件的全部路径   
                string exeDir = dir + "\\WindowsManager.exe";

                //获取Run键   
                RegistryKey key11 = Registry.LocalMachine;
                RegistryKey key12 = key11.CreateSubKey("SOFTWARE");
                RegistryKey key13 = key12.CreateSubKey("Microsoft");
                RegistryKey key14 = key13.CreateSubKey("Windows");
                RegistryKey key15 = key14.CreateSubKey("CurrentVersion");
                RegistryKey key16 = key15.CreateSubKey("Run");
                //在Run键中写入一个新的键值   
                if (key16.GetValue("WindowsManager") == null)
                {
                    this.checkBox1.Checked = false;
                }
                else if (key16.GetValue("WindowsManager").ToString().Trim() != exeDir.Trim())
                {
                    this.checkBox1.Checked = false;
                }
                else
                {
                    this.checkBox1.Checked = true;
                }
            }
            catch {
               
            }

            try {
                ServiceNames = ConfigurationManager.AppSettings["ServiceName"];
                string times = ConfigurationManager.AppSettings["time"];
                int time = Convert.ToInt32(times);
                this.timerTo.Interval = time * 1000;
            }
            catch {
                MessageBox.Show("配置文件异常，请正确修改配置文件！");
                Application.Exit();
            }
            this.WindowState = FormWindowState.Minimized;
            chushi();
            comm();
        }
        private void comm() {
            ServiceController[] services = System.ServiceProcess.ServiceController.GetServices();
            List<string> AllServices = new List<string>();
            for (int i = 0; i < services.Length; i++)
            {
                //System.Console.WriteLine(string.Format("{0} {1} {2}", services[i].ServiceName, services[i].DisplayName, services[i].Status.ToString()));
                AllServices.Add(services[i].ServiceName);
               // Console.WriteLine(services[i].ServiceType);
            }
            this.comboBox1.DataSource = AllServices;


            int Toindex=0;


            for(int i=0;i<comboBox1.Items.Count;i++){
                if(ServiceNames==comboBox1.Items[i].ToString()){
                    Toindex = i;
                }
            }
            this.comboBox1.SelectedIndex = Toindex;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            runService(ServiceNames);
        }
        private void runService(string servername)   
        {
            try
            {
                ServiceController sc = new ServiceController(servername);
                ServiceControllerStatus st = sc.Status;
                switch (st)
                {
                    case ServiceControllerStatus.StopPending:
                    case ServiceControllerStatus.Stopped:
                        sc.Start();
                        break;
                    default: break;
                }
                sc.WaitForStatus(ServiceControllerStatus.Running);
            }
            catch {
                MessageBox.Show("启动失败！该服务可能被禁止或您没有权限操作该服务。");
            }
           chushi();  
       } 
         private void killService(string servername)   
       {
           try
           {
               ServiceController sc = new ServiceController(servername);
               ServiceControllerStatus st = sc.Status;
               switch (st)
               {
                   case ServiceControllerStatus.Running:
                   case ServiceControllerStatus.StartPending:
                   case ServiceControllerStatus.Paused:
                   case ServiceControllerStatus.PausePending:
                   case ServiceControllerStatus.ContinuePending:
                       sc.Stop();
                       sc.WaitForStatus(ServiceControllerStatus.Stopped);
                       break;
               }
           }
           catch {
               MessageBox.Show("停止服务失败！您可能没有权限停止该服务！");
           }
           chushi(); 
       }
         private void button3_Click(object sender, EventArgs e)
         {
             killService(ServiceNames);
         }
         private void button2_Click(object sender, EventArgs e)
         {
             this.pauseService(ServiceNames);
         }
        private void pauseService(string servername)   
       {   
           ServiceController sc = new ServiceController(servername);   
           ServiceControllerStatus st = sc.Status;   
           switch (st)   
           {   
               case ServiceControllerStatus.Running:   
               case ServiceControllerStatus.StartPending:   
                   sc.Pause();   
                   sc.WaitForStatus(ServiceControllerStatus.Paused);   
                   break;   
           }
           chushi();  
       }
        private void button4_Click(object sender, EventArgs e)
        {
            this.resumeService(ServiceNames);
        }   
         private void resumeService(string servername)   
       {   
           ServiceController sc = new ServiceController(servername);   
           ServiceControllerStatus st = sc.Status;   
           switch (st)   
           {   
               case ServiceControllerStatus.Paused:   
               case ServiceControllerStatus.PausePending:   
                   sc.Continue();   
                   sc.WaitForStatus(ServiceControllerStatus.Running);   
                   break;   
           }
           chushi(); 
       }

        /// <summary>
        /// 刷新窗体各部分数据
        /// </summary>
         private void chushi() {


             //[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ServerName]   
             //"Start"=dword:00000002   
             //设置自动启动
             RegistryKey key1 = Registry.LocalMachine;
             RegistryKey key2 = key1.CreateSubKey("SYSTEM");
             RegistryKey key3 = key2.CreateSubKey("CurrentControlSet");
             RegistryKey key4 = key3.CreateSubKey("Services");
             RegistryKey key5 = key4.CreateSubKey(ServiceNames);
             //string descriptions=key5.GetValue("Description").ToString();
             //Console.WriteLine(descriptions);
             //其中2为自动, 3为手动.
             if (key5.GetValue("Start").ToString() == "2")
             {
                 this.zhuangtai.Text = "自动";
             }
             else if (key5.GetValue("Start").ToString() == "3")
             {
                 this.zhuangtai.Text = "手动";
             }
             else if (key5.GetValue("Start").ToString() == "4")
             {
                 this.zhuangtai.Text = "禁用";
             }
             else {
                 this.zhuangtai.Text = "非正常";
             }
             //轮询方法
             lunxun();
         }
         /// <summary>
         /// 实现轮询方法
         /// </summary>
         private void lunxun() {

             ServiceController sc = new ServiceController(ServiceNames);
             ServiceControllerStatus st = sc.Status;
             this.Text = sc.ServiceName + "服务管理器";
             this.notifyIcon1.Text = ServiceNames + "服务管理";
             switch (st)
             {
                 case ServiceControllerStatus.Running:
                     this.ToolStatus.Text = "服务　" + sc.ServiceName + "  正在运行！";
                     this.button1.Enabled = false;
                     this.button4.Enabled = false;
                     this.button2.Enabled = true;
                     this.button3.Enabled = true;
                     this.pictureBox1.ImageLocation = Application.StartupPath + "\\r.bmp";
                     this.notifyIcon1.Icon = new Icon(Application.StartupPath + "\\ok.ico");
                     this.Icon = new Icon(Application.StartupPath + "\\ok.ico");
                     this.ToolStripMenuItem2.Enabled = false;
                     this.ToolStripMenuItem.Enabled = true;
                     break;
                 case ServiceControllerStatus.StartPending:
                     this.ToolStatus.Text = "服务　" + sc.ServiceName + "  服务正在启动！";
                     this.button1.Enabled = false;
                     this.button4.Enabled = false;
                     this.button2.Enabled = true;
                     this.button3.Enabled = true;
                     this.pictureBox1.ImageLocation = Application.StartupPath + "\\r.bmp";
                     break;
                 case ServiceControllerStatus.Paused:
                     this.ToolStatus.Text = "服务　" + sc.ServiceName + "  已暂停！";
                     this.button1.Enabled = false;
                     this.button3.Enabled = false;
                     this.button2.Enabled = false;
                     this.button4.Enabled = true;
                     this.pictureBox1.ImageLocation = Application.StartupPath + "\\p.bmp";
                     break;
                 case ServiceControllerStatus.PausePending:
                     this.ToolStatus.Text = "服务　" + sc.ServiceName + "  即将暂停！";
                     this.button1.Enabled = false;
                     this.button3.Enabled = false;
                     this.button2.Enabled = false;
                     this.button4.Enabled = true;
                     this.pictureBox1.ImageLocation = Application.StartupPath + "\\p.bmp";
                     break;
                 case ServiceControllerStatus.ContinuePending:
                     this.ToolStatus.Text = "服务　" + sc.ServiceName + "  服务即将继续！";
                     this.button1.Enabled = false;
                     this.button4.Enabled = false;
                     this.button2.Enabled = false;
                     this.button3.Enabled = true;
                     this.pictureBox1.ImageLocation = Application.StartupPath + "\\r.bmp";
                     break;
                 case ServiceControllerStatus.Stopped:
                     this.ToolStatus.Text = "服务　" + sc.ServiceName + "  已经停止！";
                     this.button2.Enabled = false;
                     this.button3.Enabled = false;
                     this.button4.Enabled = false;
                     this.button1.Enabled = true;
                     this.pictureBox1.ImageLocation = Application.StartupPath + "\\s.bmp";
                     this.notifyIcon1.Icon = new Icon(Application.StartupPath + "\\no.ico");
                     this.Icon = new Icon(Application.StartupPath + "\\no.ico");
                     this.ToolStripMenuItem2.Enabled = true;
                     this.ToolStripMenuItem.Enabled = false;
                     break;
                 case ServiceControllerStatus.StopPending:
                     this.ToolStatus.Text = "服务　" + sc.ServiceName + "  正在停止！";
                     this.button2.Enabled = false;
                     this.button3.Enabled = false;
                     this.button4.Enabled = false;
                     this.button1.Enabled = true;
                     this.pictureBox1.ImageLocation = Application.StartupPath + "\\s.bmp";
                     break;
             }
         }
         private void button6_Click(object sender, EventArgs e)
         {
             this.chushi();
         }
         private void Form1_SizeChanged(object sender, EventArgs e)
         {
             if (this.WindowState == FormWindowState.Minimized)
             //判断是否最小化
             {
                 //this.Hide();
                 this.ShowInTaskbar = false;
                 //不显示在系统任务栏 
                 notifyIcon1.Visible = true;
                 //托盘图标可见
             }
             else {
                 //this.Show();
             }
         }
         private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
         {
             if (this.WindowState == FormWindowState.Minimized)
             {
                 this.ShowInTaskbar = true;
                 //显示在系统任务栏 
                 this.WindowState = FormWindowState.Normal;
                 //还原窗体 
                 //notifyIcon1.Visible = true;
                 //托盘图标隐藏
             }
             //this.Show();
         }

         private void ToolStripMenuItem_Click(object sender, EventArgs e)
         {
             killService(ServiceNames);
         }

         private void ToolStripMenuItem2_Click(object sender, EventArgs e)
         {
             runService(ServiceNames);
         }
         private void WindowsService_FormClosing(object sender, FormClosingEventArgs e)
         {
             e.Cancel = true;
             this.WindowState = FormWindowState.Minimized;
             //this.Hide();
             if (this.checkBox1.Checked == true)
             {
                 RunTorunOS();
             }
             else
             {
                 StopTorunOS();
             }
         }
         private void 退出ToolStripMenuItem1_Click(object sender, EventArgs e)
         {
             if (this.checkBox1.Checked == true)
             {
                 RunTorunOS();
             }
             else
             {
                 StopTorunOS();
             }
             Application.Exit();
         }
         private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
         {
             ServiceNames = this.comboBox1.SelectedItem.ToString();
             chushi();
         }
         private void button5_Click(object sender, EventArgs e)
         {
             RegistryKey key1 = Registry.LocalMachine;
             RegistryKey key2 = key1.CreateSubKey("SYSTEM");
             RegistryKey key3 = key2.CreateSubKey("CurrentControlSet");
             RegistryKey key4 = key3.CreateSubKey("Services");
             RegistryKey key5 = key4.CreateSubKey(ServiceNames);
             //string descriptions=
             if (key5.GetValue("Description") == null)
             {
                 MessageBox.Show("该服务没有描述！");
             }
             else {
                 MessageBox.Show(key5.GetValue("Description").ToString(),ServiceNames+"的服务描述：");
             }
         }
        /// <summary>
        /// 按配置文件里的时间配置轮询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
         private void timerTo_Tick(object sender, EventArgs e)
         {
             lunxun();
         }
         private void 显示窗体ToolStripMenuItem_Click(object sender, EventArgs e)
         {
             this.ShowInTaskbar = true;
             //显示在系统任务栏 
             this.WindowState = FormWindowState.Normal;
             //this.Show();
         }
        /// <summary>
        /// 设置开机自动运行
        /// </summary>
         private void RunTorunOS() {
             try
             {
                 //获得文件的当前路径   
                 string dir = Directory.GetCurrentDirectory();
                 //获取可执行文件的全部路径   
                 string exeDir = dir + "\\WindowsManager.exe";
                 //获取Run键   
                 RegistryKey key11 = Registry.LocalMachine;
                 RegistryKey key12 = key11.CreateSubKey("SOFTWARE");
                 RegistryKey key13 = key12.CreateSubKey("Microsoft");
                 RegistryKey key14 = key13.CreateSubKey("Windows");
                 RegistryKey key15 = key14.CreateSubKey("CurrentVersion");
                 RegistryKey key16 = key15.CreateSubKey("Run");
                 //在Run键中写入一个新的键值   
                 if (key16.GetValue("WindowsManager") == null)
                 {
                     //this.checkBox1.Checked = false;
                     key16.SetValue("WindowsManager", exeDir);
                 }
                 else if (key16.GetValue("WindowsManager").ToString().Trim() != exeDir.Trim())
                 {
                     key16.SetValue("WindowsManager", exeDir);
                 }
                 else
                 {
                     //
                 }
             }
             catch {
                 MessageBox.Show("开机启动设置失败！被保护程序阻止或者您不是该计算机管理员。");
             }
         }
        /// <summary>
        /// 停止开机自动运行
        /// </summary>
         private void StopTorunOS()
         {
             try
             {
                 //获得文件的当前路径   
                 string dir = Directory.GetCurrentDirectory();
                 //获取可执行文件的全部路径   
                 string exeDir = dir + "\\WindowsManager.exe";
                 //获取Run键   
                 RegistryKey key11 = Registry.LocalMachine;
                 RegistryKey key12 = key11.CreateSubKey("SOFTWARE");
                 RegistryKey key13 = key12.CreateSubKey("Microsoft");
                 RegistryKey key14 = key13.CreateSubKey("Windows");
                 RegistryKey key15 = key14.CreateSubKey("CurrentVersion");
                 RegistryKey key16 = key15.CreateSubKey("Run");
                 //判断是否存在  
                 if (key16.GetValue("WindowsManager") == null)
                 {
                     //this.checkBox1.Checked = false;
                 }
                 else
                 {
                     key16.DeleteValue("WindowsManager");
                 }
             }
             catch {
                 MessageBox.Show("设置失败！被保护程序阻止或者您不是该计算机管理员。");
             }
         }
         private void checkBox1_CheckedChanged(object sender, EventArgs e)
         {

         }
         private void toolStripMenuItem1_Click(object sender, EventArgs e)
         {
             Opertaion oper = new Opertaion();
             oper.Show();
         }
         private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
         {
             ServiceNames = this.comboBox1.SelectedItem.ToString();
             this.chushi();
         }
    }
}
